package services.user;

import java.util.List;

import org.springframework.transaction.annotation.Transactional;

import repositories.PersonRepository;
import services.GenericService;
import users.Person;

/**
 */
public class PersonService extends GenericService {

    private static final long serialVersionUID = 1L;

    private PersonRepository personRepository;

    public PersonRepository getPersonRepository() {
        return this.personRepository;
    }

    public void setPersonRepository(final PersonRepository personRepository) {
        this.personRepository = personRepository;
    }

    @Transactional(readOnly = true)
    public List<Person> getAllPerson() {
        return this.personRepository.findAll();
    }

    @Transactional(readOnly = true)
    // LUCAS DESPUÉS FIJATE SI ANDA COMO LA GENTE
    public Person getPersonByUsername(final String anUsername) {
        List<Person> toTrim;
        Person ret = null;

        toTrim = this.personRepository.findAll();

        for (Person it : toTrim) {
            if (it.getUserAccount().getUserID().equalsIgnoreCase(anUsername)) {
                ret = it;
            }
        }

        return ret;
    }

    @Transactional
    // LUCAS DESPUÉS FIJATE SI ANDA COMO LA GENTE
    public void updatePerson(final Person aPerson) {
        this.personRepository.update(aPerson);

    }

    @Transactional
    // LUCAS DESPUÉS FIJATE SI ANDA COMO LA GENTE
    public void createOrUpdatePerson(final Person aPerson) {
        this.personRepository.saveOrUpdate(aPerson);
    }

    @Transactional
    public void addPerson(final Person person) {
        this.personRepository.save(person);
    }

    @Transactional
    public Person getPersonByID(final Person person) {
        return this.personRepository.findById(person.getId());
    }

    @Transactional
    public List<Person> searchPersonsByUsername(final String username) {
        return this.personRepository.filterPeopleByName(username);
    }

    @Transactional
    public void deletePerson(final String anUsername) {
        Person toDelete = this.getPersonByUsername(anUsername);
        this.personRepository.delete(toDelete);
    }

    @Transactional
    public boolean authenticates(final String username, final String password) {
        Person toCheck = this.getPersonByUsername(username);
        boolean ret = false;

        if (toCheck == null) {
            return false;
        } else {
            if (toCheck != null & toCheck.getUserAccount().getUserID().equals(username)
                    & toCheck.getUserAccount().getPassword().equals(password)) {

                ret = true;
            }
        }
        return ret;
    }

    @Transactional
    public Person findById(final long id) {
        return this.getPersonRepository().findById(id);
    }

}
